package com.kuangjia.student_ems.controller;

import com.kuangjia.student_ems.dto.request.CreateNotificationRequest;
import com.kuangjia.student_ems.dto.response.NotificationResponse;
import com.kuangjia.student_ems.entity.Notification;
import com.kuangjia.student_ems.entity.User;
import com.kuangjia.student_ems.exception.NotificationException;
import com.kuangjia.student_ems.service.NotificationService;
import com.kuangjia.student_ems.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/notifications")
@Validated
public class NotificationController {
    
    private static final Logger logger = LoggerFactory.getLogger(NotificationController.class);
    
    @Autowired
    private NotificationService notificationService;
    
    @Autowired
    private UserRepository userRepository;

    /**
     * 获取用户消息列表
     * 管理员可以查看所有消息，普通用户只能查看自己的消息和系统消息
     */
    @GetMapping
    public ResponseEntity<Page<Notification>> getNotifications(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) Boolean isRead,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            // 获取当前登录用户信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String currentUsername = authentication.getName();
            User currentUser = userRepository.findByUsername(currentUsername)
                .orElseThrow(() -> new NotificationException("用户不存在"));
            
            // 如果没有指定userId，使用当前登录用户的ID
            if (userId == null) {
                userId = currentUser.getId();
            }
            
            // 检查权限：只有管理员可以查看其他用户的消息
            if (!currentUser.getRole().equals(User.UserRole.HR_ADMIN) && !userId.equals(currentUser.getId())) {
                logger.warn("用户 {} 尝试查看用户 {} 的消息，权限不足", currentUsername, userId);
                return ResponseEntity.status(403).build();
            }
            
            Page<Notification> notifications = notificationService.getNotifications(
                currentUser, userId, isRead, keyword, PageRequest.of(page, size));
            return ResponseEntity.ok(notifications);
        } catch (Exception e) {
            logger.error("获取消息列表失败，用户ID: {}", userId, e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 标记消息为已读
     */
    @PostMapping("/mark-read")
    public ResponseEntity<?> markAsRead(@RequestBody Map<String, List<Long>> body) {
        try {
            // 获取当前登录用户信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String currentUsername = authentication.getName();
            User currentUser = userRepository.findByUsername(currentUsername)
                .orElseThrow(() -> new NotificationException("用户不存在"));
            
            List<Long> ids = body.get("ids");
            notificationService.markAsRead(currentUser, ids);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            logger.error("标记消息已读失败", e);
            return ResponseEntity.badRequest().body("标记已读失败");
        }
    }

    /**
     * 删除消息
     */
    @DeleteMapping
    public ResponseEntity<?> deleteNotifications(@RequestBody Map<String, List<Long>> body) {
        try {
            // 获取当前登录用户信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String currentUsername = authentication.getName();
            User currentUser = userRepository.findByUsername(currentUsername)
                .orElseThrow(() -> new NotificationException("用户不存在"));
            
            List<Long> ids = body.get("ids");
            notificationService.deleteNotifications(currentUser, ids);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            logger.error("删除消息失败", e);
            return ResponseEntity.badRequest().body("删除消息失败");
        }
    }

    /**
     * 新增消息（管理员专用）
     */
    @PostMapping
    @PreAuthorize("hasRole('HR_ADMIN')")
    public ResponseEntity<?> createNotification(@Valid @RequestBody CreateNotificationRequest request) {
        try {
            logger.info("管理员创建消息: {}", request.getTitle());
            NotificationResponse response = notificationService.createNotification(request);
            return ResponseEntity.ok(response);
        } catch (NotificationException e) {
            logger.warn("创建消息参数错误: {}", e.getMessage());
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("创建消息失败", e);
            return ResponseEntity.badRequest().body("创建消息失败");
        }
    }
    
    /**
     * 批量发送消息给多个用户（管理员专用）
     */
    @PostMapping("/batch")
    @PreAuthorize("hasRole('HR_ADMIN')")
    public ResponseEntity<?> createNotificationsForUsers(
            @Valid @RequestBody CreateNotificationRequest request,
            @RequestParam List<Long> userIds) {
        try {
            logger.info("管理员批量发送消息给 {} 个用户: {}", userIds.size(), request.getTitle());
            List<NotificationResponse> responses = notificationService.createNotificationsForUsers(request, userIds);
            return ResponseEntity.ok(responses);
        } catch (NotificationException e) {
            logger.warn("批量发送消息参数错误: {}", e.getMessage());
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("批量发送消息失败", e);
            return ResponseEntity.badRequest().body("批量发送消息失败");
        }
    }
    
    /**
     * 发送系统消息（所有用户可见，管理员专用）
     */
    @PostMapping("/system")
    @PreAuthorize("hasRole('HR_ADMIN')")
    public ResponseEntity<?> createSystemNotification(@Valid @RequestBody CreateNotificationRequest request) {
        try {
            logger.info("管理员发送系统消息: {}", request.getTitle());
            List<NotificationResponse> responses = notificationService.createSystemNotification(request);
            return ResponseEntity.ok(responses);
        } catch (Exception e) {
            logger.error("发送系统消息失败", e);
            return ResponseEntity.badRequest().body("发送系统消息失败");
        }
    }

    /**
     * 获取未读消息数量
     */
    @GetMapping("/unread-count")
    public ResponseEntity<Long> countUnread(@RequestParam(required = false) Long userId) {
        try {
            // 获取当前登录用户信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String currentUsername = authentication.getName();
            User currentUser = userRepository.findByUsername(currentUsername)
                .orElseThrow(() -> new NotificationException("用户不存在"));
            
            // 如果没有指定userId，使用当前登录用户的ID
            if (userId == null) {
                userId = currentUser.getId();
            }
            
            // 检查权限：只有管理员可以查看其他用户的未读消息数量
            if (!currentUser.getRole().equals(User.UserRole.HR_ADMIN) && !userId.equals(currentUser.getId())) {
                logger.warn("用户 {} 尝试查看用户 {} 的未读消息数量，权限不足", currentUsername, userId);
                return ResponseEntity.status(403).build();
            }
            
            Long count = notificationService.countUnread(currentUser, userId);
            return ResponseEntity.ok(count);
        } catch (Exception e) {
            logger.error("获取未读消息数量失败，用户ID: {}", userId, e);
            return ResponseEntity.badRequest().build();
        }
    }
} 